<?php
namespace Home\Controller;

class FansController extends\Home\Controller\BaseController
{
	/**
	 * 查询用户粉丝列表
	 * @author 尹雷
	 */
	public function fansList()
	{
		$param = I('params');
		$option['page'] = I('data.page', '', '/^[1-9]\d*$/', $param) ? $param['page'] : 1;
		$option['size'] = I('data.size', '', '/^[1-9]\d*$/', $param) ? $param['size'] : 5;
		$fans = M('Fans');
		$list = $this->returnList($fans, array('user_id' => $this->user['userId']), 'create_time desc', 'id,user_id,fans_id,create_time', $option);
	
		//查询失败
		if($list === false) {
			$this->errorLog(__FILE__, __LINE__, $fans->getDbError() . '---' . $fans->getError());
			$this->ajaxReturn(array('error' => 1, 'info' => '查询失败'));
		}
	
		//查询成功
		$return = array('error' => 0, 'info' => '');
		//有数据
		if($list) {
			//构造查询用户头像条件
			$userIds = array();
			foreach($list as $key => $val) {
				$userIds[] = $val['fans_id'];
			}
			$where['u.id'] = array('in', $userIds);
			
			//查询用户头像
			$avatars = D('User')->avatar($where);
			
			//处理查询结果
			foreach($list as $key => &$val) {
				if($avatars) {
					foreach($avatars as $item) {
						if($val['fans_id'] === $item['id']) {
							$val['avatar_url'] = $item['url'];
							break;
						}
					}
				} 
				
				if(!$val['avatar_url']) {
					$val['avatar_url'] = false;
				}
			}
			
			$return['info'] = array('code' => 0, 'data' => $list);
			//无数据
		} else {
			$return['info'] = array('code' => 1, 'data' => '查无数据');
		}
		
		$this->ajaxReturn($return);
	}
	
	/**
	 * 添加关注
	 * @author 尹雷
	 */
	public function addFollow()
	{
		$param = I('params');
		$userId = I('data.user_id', '', '/^[1-9]\d*$/', $param);
		if(!$userId) $this->ajaxReturn(array('error' => 1, 'info' => '参数错误'));
		
		$data['user_id'] = $userId;
		$data['fans_id'] = $this->user['userId'];
		
		//判断是否关注过此用户
		$res = $this->returnOne('Fans', $data);
		if($res) $this->ajaxReturn(array('error' => 1, 'info' => '您已关注过该用户'));
		
		$res = D('Fans')->addFans($data);
		//添加出错
		if($res === 2) {
			$this->errorLog(__FILE__, __LIINE__, $res['info']);
			$this->ajaxReturn(array('error' => 1, 'info' => '关注失败'));
		}
		
		$this->ajaxReturn($res);
	}
	
	/**
	 * 取消关注
	 * @author 尹雷
	 */
	public function cancelFollow()
	{
		$param = I('params');
		$id = I('data.id', '', '/^[1-9]\d*$/', $param);
		if(!$id) $this->ajaxReturn(array('error' => 1, 'info' => '参数错误'));
	
		$data['id'] = $id;
		
		//判断是否关注过此用户
		$res = $this->returnOne('Fans', $data);
		if(!$res) $this->ajaxReturn(array('error' => 1, 'info' => '您没有关注过该用户'));
		
		//取消关注
		$data['status'] = -1;
		$res = D('Fans')->editFans($data);
		
		//编辑出错
		if($res === 2) {
			$this->errorLog(__FILE__, __LIINE__, $res['info']);
			$this->ajaxReturn(array('error' => 1, 'info' => '取消关注失败'));
		}
	
		$this->ajaxReturn($res);
	}
}